import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewTreeObserver
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.taobaounion.R
import com.example.taobaounion.base.BaseFragment
import com.example.taobaounion.model.bean.CategoryPagerData
import com.example.taobaounion.net.Constants
import com.example.taobaounion.presenter.impl.CategoryPagerPresenterImpl
import com.example.taobaounion.view.ICategoryPagerCallBack
import com.example.taobaounion.ui.activity.DiscountTicketActivity
import com.example.taobaounion.ui.adapter.CategoryContentAdapter
import com.example.taobaounion.ui.widget.MyNestedScrollView
import com.example.taobaounion.utils.PresenterManager
import com.scwang.smart.refresh.layout.SmartRefreshLayout


/**
 *@author : Administrator
 *@descreption : 各个分类的Fragment
 */
class CategoryFragment() : BaseFragment(), ICategoryPagerCallBack ,CategoryContentAdapter.OnGoodsItemClick{
    private lateinit var mTitleTV: TextView
    private lateinit var mNestedScrollView : MyNestedScrollView
    private lateinit var mRefreshLayout: SmartRefreshLayout

    //  private lateinit var mRefreshLayout: TwinklingRefreshLayout
    private lateinit var adapter: CategoryContentAdapter
    private var mData = ArrayList<CategoryPagerData.DataBean>()
    private var mRecyclerView: RecyclerView? = null
    private var page: Int = 1
    private var mMaterialId: Int? = 0
    private lateinit var mCategoryPagerPresenterImpl: CategoryPagerPresenterImpl
    private var mGoodsTitle :String? = null

    companion object {
        fun newInstance(materialId: Int, title: String): CategoryFragment {
            val args = Bundle()
            args.putInt(Constants.KEY_MATERIAL_ID, materialId)
            args.putString(Constants.KEY_TITLE,title)

            val fragment = CategoryFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun setPresenter() {
        mCategoryPagerPresenterImpl = PresenterManager.getInstance().categoryPagerPresenterImpl
        mCategoryPagerPresenterImpl.registerCallBack(this)
    }


    override fun initView(container: View) {
        mMaterialId = arguments?.getInt(Constants.KEY_MATERIAL_ID)
        mGoodsTitle = arguments?.getString(Constants.KEY_TITLE)

        //ReyclerView 的初始化和设置
        mRecyclerView = container.findViewById<RecyclerView>(R.id.category_content_recyclerview)
        mNestedScrollView = container.findViewById<MyNestedScrollView>(R.id.nestedScrollView)
        mTitleTV = container.findViewById<TextView>(R.id.categoryTitle)
        mTitleTV.text = mGoodsTitle



         mRefreshLayout = container.findViewById<SmartRefreshLayout>(R.id.fragment_category_home_container)

        mRefreshLayout.setOnRefreshListener { it ->
            page = 1
            mCategoryPagerPresenterImpl.reLoad(mMaterialId!!)
            Log.i("TAG", "刷新 "); }
        mRefreshLayout.setOnLoadMoreListener { refreshlayout ->
               // refreshlayout.finishLoadMore(2000) //传入false表示加载失败
            mCategoryPagerPresenterImpl.loadMore(mMaterialId!!, ++page)
                Log.i("TAG", "加载更多 ");
        }



        //动态设置RecyclerView的高度
        mRefreshLayout.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                val headHeight = mTitleTV.measuredHeight
                mNestedScrollView.setHeardHeight(headHeight)
                val containerMeasureHeight = mRefreshLayout.measuredHeight
              //  Log.i("TAG", "homeContainer.layoutParams.height =>>>>>>  $materialId     ${mRefreshLayout.layoutParams.height}    ${mRefreshLayout.measuredHeight}  ${mRecyclerView?.height} ");
                val containerParams: LinearLayout.LayoutParams = mRecyclerView?.layoutParams as LinearLayout.LayoutParams
                containerParams?.height = containerMeasureHeight
                mRecyclerView?.layoutParams = containerParams
                if (containerMeasureHeight != 0) {
                    mRefreshLayout.viewTreeObserver.removeOnGlobalLayoutListener(this)
                }
             //   Log.i("TAG", "after homeContainer.layoutParams.height =>>>>>>  $materialId     ${mRefreshLayout.layoutParams.height}    ${mRefreshLayout.layoutParams.height}  ${mRecyclerView?.layoutParams?.height}    ${mRecyclerView?.measuredHeight} ");

            }

        })

        if (mRecyclerView == null) {
            return
        }
        //设置布局manager
        mRecyclerView?.layoutManager = LinearLayoutManager(context)
        //设置item间的分割线
        mRecyclerView?.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                outRect.bottom = 8
                outRect.top = 8
            }
        })
        //创建适配器
        adapter = CategoryContentAdapter()
        adapter.setData(mData)
        adapter.setOnGoodsItemClick(this)
        //设置适配器
        mRecyclerView?.adapter = adapter

        // page = arguments!!.getInt(Constants.KEY_PAGE)

/*        //刷新控件的初始化和设置监听
        mRefreshLayout = container.findViewById(R.id.refreshLayout)
        mRefreshLayout.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                Log.i("TAG", "进入了 onLoadMore");
                mCategoryPagerPresenterImpl.loadMore(materialId!!, ++page)
            }

            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                Log.i("TAG", "进入了 onRefresh");
                page = 1
                mCategoryPagerPresenterImpl.reLoad(materialId!!)
            }
        })*/

    }

    override fun initData() {
        mCategoryPagerPresenterImpl.loadData(mMaterialId!!, page)
    }

    override fun setLayoutResourcesID(): Int {
        return R.layout.fragment_category
    }

    override fun loadSuccess(data: List<CategoryPagerData.DataBean>, id: Int) {
        if (data == null) return
        if (id != this.mMaterialId) return

        mData.clear()
        mData.addAll(data)
        setViewState(State.SUCCESS)
        adapter.setData(mData)
    }

    override fun loading(id: Int) {
        if (id != this.mMaterialId) return
        setViewState(State.LOADING)
        //

    }

    override fun loadError(id: Int) {
        if (id != this.mMaterialId) return
        setViewState(State.ERROR)

    }

    override fun noData() {
        if (id != this.mMaterialId) return
        setViewState(State.NONE)

    }

    override fun reLoadSuccess(data: List<CategoryPagerData.DataBean>, id: Int) {
        if (data == null) return
        if (id != this.mMaterialId) return
        mRefreshLayout.finishRefresh()
        //  mRefreshLayout.finishRefreshing()
        mData.clear()
        mData.addAll(data)
        setViewState(State.SUCCESS)
        adapter.setData(mData)
    }

    override fun loadMoreError(id: Int) {
        if (id != this.mMaterialId) return
        Toast.makeText(context, "数据加载出错...", Toast.LENGTH_SHORT).show()
        mRefreshLayout.finishLoadMore()

    }

    override fun loadMoreSuccess(data: List<CategoryPagerData.DataBean>, id: Int) {
        if (data == null) return
        if (id != this.mMaterialId) return
        mRefreshLayout.finishLoadMore()
        //mRefreshLayout.finishLoadmore()
        Toast.makeText(context, "加载了${data.size}条数据", Toast.LENGTH_SHORT).show()
        val size = mData.size
        mData.addAll(size, data)
        adapter.setData(mData)
    }

    override fun noMoreData() {
        if (id != this.mMaterialId) return
        Toast.makeText(context, "没有更多数据了...", Toast.LENGTH_SHORT).show()
    }


    //宝贝列表item的点击回调
    override fun onItemClickCallBack(url: String, title: String, picUrl: String) {
       val ticketPresenterImpl =  PresenterManager.getInstance().discountTicketPresenterImpl
        ticketPresenterImpl.getDiscountTicket(url,title,picUrl)
        val intent = Intent(context, DiscountTicketActivity::class.java)
        intent.putExtra("title", title)
        intent.putExtra("url", url)
        startActivity(intent)
    }


    override fun reLoadData() {
        page = 1
        mCategoryPagerPresenterImpl.reLoad(mMaterialId!!)
    }

}